package com.service.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @program: sch-diy-parent
 * @description:
 * @author: sch
 * @create: 2021-01-16 21:03
 **/
public class ServerSocketMyThreadPool {
    public static void main(String[] args) throws IOException {
        //初始化服务端socket并绑定9999端口
        ServerSocket serverSocket = new ServerSocket(8877);
        //创建线程池
        ThreadPoolExecutor threadPoolExecutor =
                new ThreadPoolExecutor(4, 8, 15, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
        //等待客户端连接
        Socket socket = serverSocket.accept();

        Runnable runnable = () -> {
            //获取输入流
            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            //读取一行数据
            String line = null;
            //循环读
            while (true) {
                try {
                    if (!((line = br.readLine()) != null)) {
                        break;
                    }
                    //打印
                    System.out.println("客户端信息:" + line);

                    //读取客户端发送来的消息
                    BufferedWriter bwT = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    bwT.write("我来自server" + "\n");
                    bwT.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
        };

        Future<?> submit = threadPoolExecutor.submit(runnable);
        System.out.println("");

    }

}
